library(tidyverse) # for graphing and data cleaning
library(gardenR) # for Lisa's garden data
library(lubridate) # for date manipulation
library(ggthemes) # for even more plotting themes
library(geofacet) # for special faceting with US map layout
theme_set(theme_minimal()) # My favorite ggplot() theme :)
# Lisa's garden data
data("garden_harvest")
# Seeds/plants (and other garden supply) costs
data("garden_spending")
# Planting dates and locations
data("garden_planting")
# Tidy Tuesday data
kids <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-15/kids.csv')
Before starting your assignment, you need to get yourself set up on GitHub and make sure GitHub is connected to R Studio. To do that, you should read the instruction (through the “Cloning a repo” section) and watch the video here. Then, do the following (if you get stuck on a step, don’t worry, I will help! You can always get started on the homework and we can figure out the GitHub piece later):
keep_md: TRUE in the YAML heading. The .md file is a markdown (NOT R Markdown) file that is an interim step to creating the html file. They are displayed fairly nicely in GitHub, so we want to keep it and look at it there. Click the boxes next to these two files, commit changes (remember to include a commit message), and push them (green up arrow).Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Expanding the data wrangling toolkit” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
garden_harvest data to find the total harvest weight in pounds for each vegetable and day of week (HINT: use the wday() function from lubridate). Display the results so that the vegetables are rows but the days of the week are columns.garden_harvest %>%
mutate(day = wday(date, label = TRUE)) %>%
group_by(vegetable, day) %>%
summarise(daily_weight = sum(weight)) %>%
pivot_wider(id_cols = vegetable,
names_from = day,
values_from = daily_weight)
garden_harvest data to find the total harvest in pound for each vegetable variety and then try adding the plot from the garden_planting table. This will not turn out perfectly. What is the problem? How might you fix it?garden_harvest %>%
group_by(variety) %>%
summarize(total_harvest = sum(weight)) %>%
left_join(garden_planting,
by = "variety")
# The problem is that some varieties are planted in multiple plots, leading them to be reported twice when we join the two tables. One way to fix this might be to create a new variable "total_plots" that contains all the plots a variety is planted in.
garden_harvest and garden_spending datasets, along with data from somewhere like this to answer this question. You can answer this in words, referencing various join functions. You don’t need R code but could provide some if it’s helpful.To answer this question, I would first join the garden_spending dataset to the garden_harvest dataset by variety, using a left join. Next, I would create a dataset of grocery store vegetable costs, with variables such as vegetable, variety, cost, cost with tax, etc. Once this new dataset (lets call it store_prices) is created, then I would join store_prices to garden_harvest using a left join. From here, I would use various wrangling functions to sum different combinations of variables to calculate how much money was saved.
plant_min_date <- garden_planting %>%
group_by(vegetable, variety) %>%
summarize(first_plant_date = min(date))
garden_harvest %>%
filter(vegetable == "tomatoes") %>%
mutate(varieties_reorder = fct_reorder(variety, date)) %>%
group_by(varieties_reorder) %>%
summarize(total_harvest = sum(weight)) %>%
ggplot(aes(y = varieties_reorder, x = total_harvest)) +
geom_col() +
labs(title = "Total Harvest for Tomato Varieties",
x = "Total Harvest in Grams",
y = "")
garden_harvest data, create two new variables: one that makes the varieties lowercase and another that finds the length of the variety name. Arrange the data by vegetable and length of variety name (smallest to largest), with one row for each vegetable variety. HINT: use str_to_lower(), str_length(), and distinct().garden_harvest %>%
mutate(varieties_lower = str_to_lower(variety),
variety_length = str_length(variety)) %>%
distinct(variety, .keep_all = TRUE) %>%
arrange(vegetable, variety_length)
garden_harvest data, find all distinct vegetable varieties that have “er” or “ar” in their name. HINT: str_detect() with an “or” statement (use the | for “or”) and distinct().garden_harvest %>%
mutate(has_er_ar = str_detect(variety, "er|ar")) %>%
distinct(variety, .keep_all = TRUE)
In this activity, you’ll examine some factors that may influence the use of bicycles in a bike-renting program. The data come from Washington, DC and cover the last quarter of 2014.
{300px}
{300px}
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
NOTE: The Trips data table is a random subset of 10,000 trips from the full quarterly data. Start with this small data table to develop your analysis commands. When you have this working well, you should access the full data set of more than 600,000 events by removing -Small from the name of the data_site.
It’s natural to expect that bikes are rented more at some times of day, some days of the week, some months of the year than others. The variable sdate gives the time (including the date) that the rental started. Make the following plots and interpret them:
sdate. Use geom_density().Trips %>%
ggplot(aes(x = sdate)) +
geom_density() +
labs(title = "When Bike Trips Occured",
x = "Start Date of Event",
y = "Density")
mutate() with lubridate’s hour() and minute() functions to extract the hour of the day and minute within the hour from sdate. Hint: A minute is 1/60 of an hour, so create a variable where 3:30 is 3.5 and 3:45 is 3.75.Trips %>%
mutate(time_day = hour(sdate) + minute(sdate)/60) %>%
ggplot(aes(x = time_day)) +
geom_density() +
labs(title = "When in the Day Trips Occured",
x = "Hour",
y = "Density")
Trips %>%
mutate(day = wday(sdate,
label = TRUE,
week_start = getOption("lubridate.week.start", 7))) %>%
ggplot(aes(y = day)) +
geom_bar() +
labs(title = "Bike Event vs. Day of Week",
x = "Number of Events",
y = "")
Trips %>%
mutate(time_day = hour(sdate) + minute(sdate)/60,
day = wday(sdate,
label = TRUE,
week_start = getOption("lubridate.week.start", 7))) %>%
ggplot(aes(x = time_day)) +
geom_density() +
facet_wrap(~ day) +
labs(title = "Bike Event vs. Day of Week",
x = "Time of Day",
y = "Density")
There appears to be a pattern with the weekdays having a bimodal density plot at times of major commuting in the early morning and late afternoon. On the weekends, there is much more continuous activity throughout the day.
The variable client describes whether the renter is a regular user (level Registered) or has not joined the bike-rental organization (Causal). The next set of exercises investigate whether these two different categories of users show different rental behavior and how client interacts with the patterns you found in the previous exercises.
fill aesthetic for geom_density() to the client variable. You should also set alpha = .5 for transparency and color=NA to suppress the outline of the density function.Trips %>%
mutate(time_day = hour(sdate) + minute(sdate)/60,
day = wday(sdate,
label = TRUE,
week_start = getOption("lubridate.week.start", 7))) %>%
ggplot() +
geom_density(aes(x = time_day, fill = client), alpha = 0.5, color = NA) +
scale_fill_brewer(palette = "Set1") +
facet_wrap(~ day) +
labs(title = "Bike Event vs. Day of Week",
subtitle = "By Clinet Type",
x = "Time of Day",
y = "Density",
fill = "Client")
position = position_stack() to geom_density(). In your opinion, is this better or worse in terms of telling a story? What are the advantages/disadvantages of each?Trips %>%
mutate(time_day = hour(sdate) + minute(sdate)/60,
day = wday(sdate,
label = TRUE)) %>%
ggplot() +
geom_density(aes(x = time_day, fill = client), alpha = 0.5, color = NA, position = position_stack()) +
scale_fill_brewer(palette = "Set1") +
facet_wrap(~ day) +
labs(title = "Bike Event vs. Day of Week",
subtitle = "By Clinet Type",
x = "Time of Day",
y = "Density",
fill = "Client")
In my opinion, the second graph is better as its less cluttered visually. While it might make comparison harder, it does a better job at showing distinctions between trends in the client types.
position = position_stack()). Add a new variable to the dataset called weekend which will be “weekend” if the day is Saturday or Sunday and “weekday” otherwise (HINT: use the ifelse() function and the wday() function from lubridate). Then, update the graph from the previous problem by faceting on the new weekend variable.Trips %>%
mutate(time_day = hour(sdate) + minute(sdate)/60,
day = wday(sdate,
label = TRUE),
weekend = ifelse(day == c("Sat", "Sun"), "weekend", "weekday")) %>%
ggplot() +
geom_density(aes(x = time_day, fill = client), alpha = 0.5, color = NA) +
scale_fill_brewer(palette = "Set1") +
facet_wrap(~ weekend) +
labs(title = "Bike Usage: Weekend vs. Weekday",
subtitle = "By Client Type",
x = "Time of Day",
y = "Density",
fill = "Client")
client and fill with weekday. What information does this graph tell you that the previous didn’t? Is one graph better than the other?Trips %>%
mutate(time_day = hour(sdate) + minute(sdate)/60,
day = wday(sdate,
label = TRUE),
weekend = ifelse(day == c("Sat", "Sun"), "weekend", "weekday"),
weekday = weekend == "weekday") %>%
ggplot() +
geom_density(aes(x = time_day, fill = weekday), alpha = 0.5, color = NA) +
scale_fill_brewer(palette = "Set1") +
facet_wrap(~ client) +
labs(title = "Ridership by Rider Type and Time of Week",
x = "Time of Day",
y = "Density") +
scale_fill_discrete(name = "", labels = c("Weekend", "Weekday"))
I think the second graph does a better job of showing how consistent trends are for casual riders vs. registered riders. I think they serve different purposes, and therefore neither is inherently “better” than the other.
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. We will improve this plot next week when we learn about maps!Trips %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
group_by(lat, long) %>%
count(sstation, name = "departure_count") %>%
ggplot(aes(x = long, y = lat, color = departure_count)) +
scale_color_gradient(low="blue", high="red") +
geom_point() +
labs(title = "Total Number of Departures From Each Station",
x = "Longitude Coordinates of Station",
y = "Latitude Corrdinates pf Station",
color = " # of Departures")
Trips %>%
left_join(Stations,
by = c("sstation" = "name")) %>%
group_by(client) %>%
mutate(casual_true = client == "Casual",
reg_true = client == "Registered") %>%
group_by(sstation, lat, long) %>%
summarize(sum_rider = mean(casual_true) > mean(reg_true)) %>%
ggplot(aes(x = long, y = lat, color = sum_rider)) +
scale_color_discrete(name = "Highest Percentage Rider Status", labels = c("Registered", "Casual")) +
geom_point() +
labs(title = "Stations with Higher Percentage of Departures by Casual Users",
x = "Longitude",
y = "Latitude")
One thing that I notice is that there is clustering of higher casual riders at stations at around (38.9, -77.05). This might be due to some kind of commerical area that has a lot of exposure to many different kinds of people.
as_date(sdate) converts sdate from date-time format to date format.top_ten_departures <- Trips %>%
mutate(date_only = as_date(sdate)) %>%
group_by(sstation, date_only) %>%
count(sstation, sort = TRUE, name = "num_depart") %>%
head(n = 10)
top_ten_departures
#find station-date combinations
#find number of departures from each station-date combination
Trips %>%
mutate(date_only = as_date(sdate),
day = wday(sdate,
label = TRUE)) %>%
inner_join(top_ten_departures,
by = c("sstation", "date_only"))
Trips %>%
mutate(date_only = as_date(sdate),
day = wday(sdate,
label = TRUE)) %>%
inner_join(top_ten_departures,
by = c("sstation", "date_only")) %>%
group_by(client, day) %>%
summarize(prop_client_type = n()) %>%
mutate(prop = prop_client_type/ sum(prop_client_type)) %>%
pivot_wider(names_from = client,
values_from = prop)
From these results, we can see that the proportion of trips by casual clients take place predominately on the weekends for the station-date combos with the highest departures per day. For registered clients, the proportions of trips are much more evenly spread across the weekdays, with significant usage on Sundays as well.
DID YOU REMEMBER TO GO BACK AND CHANGE THIS SET OF EXERCISES TO THE LARGER DATASET? IF NOT, DO THAT NOW.
This problem uses the data from the Tidy Tuesday competition this week, kids. If you need to refresh your memory on the data, read about it here.
facet_geo(). The graphic won’t load below since it came from a location on my computer. So, you’ll have to reference the original html on the moodle page to see it.kids %>%
pivot_wider(names_from = variable,
values_from = raw:inf_adj_perchild) %>%
group_by(state, year) %>%
select(inf_adj_perchild_lib) %>%
group_by(year) %>%
filter(year == c(1997, 2016)) %>%
group_by(state) %>%
mutate(lib_2016 = ifelse(year == 2016, inf_adj_perchild_lib, 0),
lib_1997 = ifelse(year == 1997, inf_adj_perchild_lib, 0)) %>%
summarize(lib_change = lib_2016 - lib_1997) %>%
ggplot(aes(x = state, y = lib_change)) +
geom_line() +
facet_geo(~ state, scales = "free")
DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?